# encoding=utf-8
import base64
import json
from scrapy.exceptions import IgnoreRequest
from scrapy.utils.project import get_project_settings

from jesgcc.utils.sm4 import CryptSM4, SM4_DECRYPT


class SM4DecryptMiddleware(object):
    """
    SM4解密中间件
    """

    def __init__(self):
        settings = get_project_settings()
        # 密钥
        sm4_key = settings.get('SM4_KEY', 'e@s#g$c%c_l&o*g_i@n')
        # 解密对象
        self.crypt_sm4 = CryptSM4()
        self.crypt_sm4.set_key(bytes(sm4_key, encoding="utf8"), SM4_DECRYPT)

    def process_request(self, request, spider):
        pass

    def process_response(self, request, response, spider):
        meta = request.meta
        if meta and 'reqType' in meta:
            req_type = meta.get('reqType')
            if req_type in ['sku'] and response.text:
                rs = json.loads(response.text)
                if rs and rs.get('data', ''):
                    data = rs.get('data', '')
                    decrypt_value = self.crypt_sm4.crypt_ecb(base64.b64decode(data))
                    js = json.loads(decrypt_value)
                    request.meta['decode_json'] = js

        return response

    def process_exception(self, request, exception, spider):
        _ = request
        _ = exception
        if not isinstance(exception, IgnoreRequest):
            spider.logger.error('decode error: {}'.format(exception))
